package cn.netjava.robo3d.device;

import cn.netjava.robo3d.RoboTank;

import com.jme.math.FastMath;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.scene.Spatial;

/**
 * 我的追踪摄像机
 * @author westice
 *
 */
public class ChaserCam {

	private float mindistance=0.2f;  //和物体的最小距离
	private float maxdistance=1.5f;  //和物体的最大距离
	private float alpha=0;
	private static float minspeed=7f;      //最小追踪速度
	private float speed=minspeed;
	private float height=1.5f;       //摄像机高出物体的距离
	private Camera cam;
	private RoboTank obj;
	private Vector3f distancevec;  //摄像机到物体的向量
	private Vector3f worldUpVector=new Vector3f(0,1,0);
	private Vector3f camloc=new Vector3f();      //相机位置
	private Vector3f chaserloc=new Vector3f();   //用于追赶的位置，在物体后面

	public ChaserCam(Camera cam,RoboTank obj){
		this.cam=cam;
		this.obj=(RoboTank)obj;
	}

	public void update(float time){
        float y=obj.getLocalTranslation().y;
        if(obj.getspeed()!=0){
		  cam.getLocation().setY(y+height);   //设置高度
        }
		Vector3f camdir=new Vector3f();
		Vector3f objloc=new Vector3f();
		camloc=cam.getLocation().clone();
		camdir=cam.getDirection().clone();
		objloc=obj.getLocalTranslation().clone();
		//追赶物体后面的某一点,要把这一点放在相机追赶范围的边界上
		chaserloc=objloc.add(worldUpVector.mult(height-maxdistance));
		obj.getCardirection().normalizeLocal();
		chaserloc.addLocal(obj.getCardirection().mult(-3f));
		distancevec=chaserloc.subtract(camloc);
		float distance=distancevec.length();
		float distance2=objloc.subtract(camloc).length();
		distancevec.normalizeLocal();
		//设置相机的原始位置
		if(distance>20*maxdistance){
		   camloc=objloc.add(obj.getCardirection().mult(2*maxdistance));
		}

		//速度太快了，得加速
		if(FastMath.abs(obj.getspeed())>minspeed){
			speed=1.3f*FastMath.abs(obj.getspeed());
		}

		if(distance<mindistance){
			//太近了,离开点
			camloc=camloc.add(distancevec.mult(-speed*time));
		}
		if(distance>maxdistance){
			//远了，追啊！
			camloc=camloc.add(distancevec.mult(speed*time));
		}
    
		cam.setLocation(camloc);
		objloc.addLocal(obj.getCardirection().mult(1.5f));
		cam.lookAt(objloc, worldUpVector);
	}


}
